# -*- coding:utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:

import json


def _query_user_tag(client, uuid):
    return client.query_user_tag({'conditions': [{'name': 'resourceUuid', 'op': '=', 'value': uuid}]})


def query_image(client):
    return client.query_image()


def update_image(client, uuid, name, description):
    data = {'uuid': uuid, 'name': name, 'description': description}
    return client.update_image(data)


def query_image_by_uuid(client, uuid):
    data = {'conditions': [{'name': 'uuid', 'op': '=', 'value': uuid}]}
    return client.query_image(data)


def delete_image(client, uuid):
    data = {'uuid': uuid}
    return client.delete_image(data)


def add_image(client, name, description, media_type, platform, url, backup_storage_uuids, image_format):
    data = {
        'name': name,
        'description': description,
        'mediaType': media_type,
        'platform': platform,
        'url': url,
        'format': image_format,
        'backupStorageUuids': backup_storage_uuids
    }
    return client.add_image(data)


def query_image_property(client, uuid, key='categories'):
    tags = _query_user_tag(client, uuid)
    for tag in tags:
        try:
            tag = json.loads(tag['tag'])
        except ValueError:
            continue
        if key in tag:
            return tag[key]
    return None


def updata_image_category(client, image_uuid, category):
    category = json.dumps({'categories': category})
    tags = _query_user_tag(client, image_uuid)
    for tag in tags:
        try:
            ct = json.loads(tag['tag'])
        except ValueError:
            continue

        if 'categories' in ct:
            client.delete_tag({'uuid': tag.get('uuid')})
    return client.create_user_tag({'resourceType': 'ImageVO', 'resourceUuid': image_uuid, 'tag': category})
